package com.sunnuwell.demo.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.sunnuwell.demo.entity.User;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @program: entry
 * @description: 生成token方法
 * @author: Mr.lv
 * @create: 2019-04-24 12:07
 **/
public class Utils {
    /**
     * token 过期时间: 1小时
     */
    public static final int calendarField = Calendar.DATE;
    public static final int calendarInterval = 60;

    public static String getToken(User user) {
        String token = "";
        Date iatDate = new Date();
        // expire time
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(calendarField, calendarInterval);
        Date expiresDate = nowTime.getTime();
        token = JWT.create().withAudience(user.getCid())// 将 user id 保存到 token 里面
                .withExpiresAt(expiresDate) //设置过期时间
                .sign(Algorithm.HMAC256(user.getPassword()));// 以 password 作为 token 的密钥
        return token;
    }

    // 将字符串转化时间
    public static Integer parseTime(String s) throws ParseException {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
        Date date = simpleDateFormat.parse(s);
        Integer ts = Integer.valueOf((int) (date.getTime()/1000));
        return ts;
    }

    // 将字符串转化时间
    public static Integer parseTime2(String s) throws ParseException {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = simpleDateFormat.parse(s);
        Integer ts = Integer.valueOf((int) (date.getTime()/1000));
        return ts;
    }
}